package com.wtx.fitness.util;

import io.jsonwebtoken.Claims;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;

/**
 * Token工具类
 */
public class TokenUtil {

  /**
   * 获取请求中的token
   */
  public static String getToken() {
    try {
      HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
          .getRequest();
      String token = request.getHeader("Authorization");

      // 去掉Bearer前缀
      if (token != null && token.startsWith("Bearer ")) {
        token = token.substring(7);
      }

      return token;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  /**
   * 获取用户ID
   */
  public static String getUserId() {
    try {
      String token = getToken();
      if (token == null || token.isEmpty()) {
        return null;
      }

      Claims claims = JwtUtil.parseJWT(token);
      if (claims == null) {
        return null;
      }

      return claims.getSubject();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  /**
   * 获取用户类型
   */
  public static String getUserType() {
    try {
      String token = getToken();
      if (token == null || token.isEmpty()) {
        return null;
      }

      Claims claims = JwtUtil.parseJWT(token);
      if (claims == null) {
        return null;
      }

      return claims.get("type", String.class);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
}